package sing.core.weight

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextSwitcher
import android.widget.TextView
import android.widget.ViewSwitcher
import sing.core.R

/**
 * 公告、新闻、广告切换
 */
class CustomTextSwitcher(val mContext: Context, attrs: AttributeSet?) : TextSwitcher(mContext, attrs), ViewSwitcher.ViewFactory {

    init {
        setFactory(this)
    }

    private var list: ArrayList<String> = arrayListOf() // 数据源
    private var timeInterval = 3000L // 默认轮播时间
    private var currentIndex = 0 // 当前第几个

    fun setInAnimation(animationResId: Int): CustomTextSwitcher {
        inAnimation = AnimationUtils.loadAnimation(mContext, animationResId)
        return this
    }

    fun setOutAnimation(animationResId: Int): CustomTextSwitcher {
        outAnimation = AnimationUtils.loadAnimation(mContext, animationResId)
        return this
    }

    /**
     * 通知/公告数据绑定
     */
    fun bindData(list: ArrayList<String>): CustomTextSwitcher {
        this.list.clear()
        this.list.addAll(list)
        return this
    }

    fun startSwitch(timeInterval: Long) {
        this.timeInterval = timeInterval
        if (list.size > 0) {
            handler.sendEmptyMessage(0)
        } else {
            throw RuntimeException("data is empty")
        }
    }

    /**
     * 工厂类中创建TextView供给TextSwitcher使用
     */
    override fun makeView(): View {
        val view = TextView(mContext)
        view.maxLines = 1
        view.setTextSize(TypedValue.COMPLEX_UNIT_PX,resources.getDimension(sing.uiadapter.R.dimen.dp_12_x))
        view.ellipsize = TextUtils.TruncateAt.END
        return view
    }

    private val handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun dispatchMessage(msg: Message) {
            super.dispatchMessage(msg)
            val index = currentIndex % list.size
            currentIndex++
            setText(list[index])
            sendEmptyMessageDelayed(0, timeInterval)
        }
    }
}